-- Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
--
-- this file licensed under the Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2
--
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-- PURPOSE.
-- See the Mulan PSL v2 for more details.
--
-- Create: 2025-5-7
-- Description: init file

local class = require 'mc.class'
local log = require 'mc.logging'
local reboot = require 'mc.mdb.micro_component.reboot'
local debug = require 'mc.mdb.micro_component.debug'
local service = require 'active_standby_mgmt.service'
local mdb_manager = require 'mc.mdb.object_manage'
local as_management = require 'active_standby_manager'
local object_management = require 'objects.manager'
local signal = require 'mc.signal'
require 'active_standby_mgmt.json_types.Accessor'

local active_standby_mgmt = class(service)

function active_standby_mgmt:init()
    log:notice('active_standby_mgmt service initializing')
    self.super.init(self)
    self.sigs = {start = signal.new(), failover = signal.new(),
        restart_service = signal.new(), restart_client = signal.new()}
    self.obj_mgmt = object_management.new(self.sigs)
    self.as_mgmt = as_management.new(self.obj_mgmt, self.sigs)
    self.as_mgmt:initialize()
    -- 初始化对象注册回调
    self:init_object_register()
    -- 平滑重启接口
    self:init_reboot()
    -- 一键日志收集接口
    debug.on_dump(function(...) self.as_mgmt:on_dump(...) end)
    log:notice('active_standby_mgmt service initialized')
end

function active_standby_mgmt:init_object_register()
    mdb_manager.on_add_object(self.bus, function(...) self:object_register(...) end)
end

function active_standby_mgmt:object_register(clz, obj)
    if clz == 'ActiveStandbyLocal' then
        self.obj_mgmt:register_as_local(obj)
        self:init_rpc()
    elseif clz == 'ActiveStandbyRemote' then
        self.obj_mgmt:register_as_remote(obj)
    elseif clz == 'SwitchRule' then
        self.obj_mgmt:register_switch_rule(obj)
    elseif clz == 'ActiveStandbyService' then
        self.obj_mgmt:register_as_service(obj)
    end
end

function active_standby_mgmt:init_rpc()
    self:ImplActiveStandbyLocalLocalSwitchStatus(function(_, ctx, status)
        return self.as_mgmt:switch_status(ctx:get_initiator(), status)
    end)
end

function active_standby_mgmt:init_reboot()
    reboot.on_prepare(function(...) self.as_mgmt:set_active_to_standby() return 0 end)
    reboot.on_action(function(...) return 0 end)
    reboot.on_cancel(function(...) end)
end

return active_standby_mgmt
